package com.ikangtai.shecare.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.ListBar;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncTaskItem;
import com.ikangtai.shecare.common.eventBusMsg.TaskListMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncTaskItemMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class ModifyTaskListActivity extends BaseActivity implements View.OnClickListener, ListBar.OnListBarClickListener {

    private TopBar topBar;
    private ListBar taskBBT, taskWater, taskMedicine, taskSport, taskFruit, taskMucus, taskLHPaper, taskBUltrasonic;
    private static final int TASK_INFO = 8;
    private DBManager dbManager;
    private static final int UPDATE_TASK_OK = 1;
    private static final int UPDATE_TASK_NOK = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_modify_task_list);
        dbManager = new DBManager(this);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                Intent intent = new Intent();
                setResult(TASK_INFO, intent);
                finish();
            }

            @Override
            public void midLeftClick() {
            }

            @Override
            public void midRightClick() {
            }

            @Override
            public void rightClick() {
                updateTaskIDs();
            }
        });

        taskBBT = (ListBar) findViewById(R.id.taskBBT);
        taskWater = (ListBar) findViewById(R.id.taskWater);
        taskMedicine = (ListBar) findViewById(R.id.taskMedicine);
        taskSport = (ListBar) findViewById(R.id.taskSport);
        taskFruit = (ListBar) findViewById(R.id.taskFruit);
        taskMucus = (ListBar) findViewById(R.id.taskMucus);
        taskLHPaper = (ListBar) findViewById(R.id.taskLHPaper);
        taskBUltrasonic = (ListBar) findViewById(R.id.taskBUltrasonic);

        taskBBT.setOnClickListener(this);
        taskBBT.setOnListBarClickListener(this);

        taskWater.setOnClickListener(this);
        taskWater.setOnListBarClickListener(this);

        taskMedicine.setOnClickListener(this);
        taskMedicine.setOnListBarClickListener(this);

        taskSport.setOnClickListener(this);
        taskSport.setOnListBarClickListener(this);

        taskFruit.setOnClickListener(this);
        taskFruit.setOnListBarClickListener(this);

        taskMucus.setOnClickListener(this);
        taskMucus.setOnListBarClickListener(this);

        taskLHPaper.setOnClickListener(this);
        taskLHPaper.setOnListBarClickListener(this);

        taskBUltrasonic.setOnClickListener(this);
        taskBUltrasonic.setOnListBarClickListener(this);

        taskInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.taskBBT:
//                setListBar(taskBBT);
                Toast.makeText(this, R.string.ModifyToast, Toast.LENGTH_SHORT).show();
                break;
            case R.id.taskWater:
                setListBar(taskWater);
                break;
            case R.id.taskMedicine:
                setListBar(taskMedicine);
                break;
            case R.id.taskSport:
                setListBar(taskSport);
                break;
            case R.id.taskFruit:
                setListBar(taskFruit);
                break;
            case R.id.taskMucus:
                setListBar(taskMucus);
                break;
            case R.id.taskLHPaper:
                setListBar(taskLHPaper);
                break;
            case R.id.taskBUltrasonic:
                setListBar(taskBUltrasonic);
                break;
        }
    }

    private void setListBar(ListBar listBar) {
        listBar.setSelected(!listBar.isSelected());
    }

    @Override
    public void rightButtonClick(ListBar listBar) {
        switch (listBar.getId()) {
            case R.id.taskBBT:
//                setListBar(taskBBT);
                Toast.makeText(this, R.string.ModifyToast, Toast.LENGTH_SHORT).show();
                break;
            case R.id.taskWater:
                setListBar(taskWater);
                break;
            case R.id.taskMedicine:
                setListBar(taskMedicine);
                break;
            case R.id.taskSport:
                setListBar(taskSport);
                break;
            case R.id.taskFruit:
                setListBar(taskFruit);
                break;
            case R.id.taskMucus:
                setListBar(taskMucus);
                break;
            case R.id.taskLHPaper:
                setListBar(taskLHPaper);
                break;
            case R.id.taskBUltrasonic:
                setListBar(taskBUltrasonic);
                break;
        }
    }

    /**
     * 拼接taskIDs数据字段
     *
     * @return
     */
    private String getTask() {
        String taskIDs = "1";

        if (taskWater.isSelected()) {
            taskIDs = taskIDs + ",2";
        }

        if (taskMedicine.isSelected()) {
            taskIDs = taskIDs + ",3";
        }

        if (taskSport.isSelected()) {
            taskIDs = taskIDs + ",4";
        }

        if (taskFruit.isSelected()) {
            taskIDs = taskIDs + ",5";
        }

        if (taskMucus.isSelected()) {
            taskIDs = taskIDs + ",6";
        }

        if (taskLHPaper.isSelected()) {
            taskIDs = taskIDs + ",7";
        }

        if (taskBUltrasonic.isSelected()) {
            taskIDs = taskIDs + ",8";
        }
        return taskIDs;
    }

    /**
     * 初始化任务显示信息
     */
    private void taskInfo() {
        taskBBT.setSelected(true);

        String taskIDs = dbManager.getSqliteKeyValue(App.userName, "taskIDs");
        if (null == taskIDs)
            taskIDs = "1,2,3";
        String[] taskIDsList = taskIDs.split(",");
        for (int i = 0; i < taskIDsList.length; i++) {
            if (Integer.valueOf(taskIDsList[i]) == 2) {
                taskWater.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 3) {
                taskMedicine.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 4) {
                taskSport.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 5) {
                taskFruit.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 6) {
                taskMucus.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 7) {
                taskLHPaper.setSelected(true);
            } else if (Integer.valueOf(taskIDsList[i]) == 8) {
                taskBUltrasonic.setSelected(true);
            }
        }
    }

    private void updateTaskIDs() {
        if (InternetUtil.hasInternet()) {
            SyncTaskItemMsg syncTaskItemMsg = new SyncTaskItemMsg();
            syncTaskItemMsg.setTaskIDs(getTask());
            SyncTaskItem syncTaskItem = new SyncTaskItem(this, syncTaskItemMsg);
            syncTaskItem.syncTaskItemWithNetwork();
        } else {
            sendNOKResp(UPDATE_TASK_NOK);
            Toast.makeText(this, R.string.network_anomalies, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上传taskID
     */
    private void postUpdateTaskIDs() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "care/updateTaskID.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("taskIDs", getTask());
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp(UPDATE_TASK_NOK);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(UPDATE_TASK_OK);
                            AppLog.i("update task ids onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            postUpdateTaskIDs();
                        } else {
                            sendNOKResp(UPDATE_TASK_NOK);
                            AppLog.i("update task ids onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("update task ids onResponse failed!");
                        sendNOKResp(UPDATE_TASK_NOK);
                        e.printStackTrace();
                    }
                }

            });
        } catch (JSONException e) {
            sendNOKResp(UPDATE_TASK_NOK);
            e.printStackTrace();
        }
    }

    @Subcriber
    private void syncTaskItem(SyncTaskItemMsg syncTaskItemMsg) {
        postUpdateTaskIDs();
    }

    private void sendNOKResp(int returnCode) {
        TaskListMsg taskListMsg = new TaskListMsg();
        taskListMsg.setRespCode(returnCode);
        EventBus.getDefault().post(taskListMsg);
    }

    private void sendOKResp(int returnCode) {
        TaskListMsg taskListMsg = new TaskListMsg();
        taskListMsg.setRespCode(returnCode);
        EventBus.getDefault().post(taskListMsg);
    }

    @Subcriber
    private void taskIDs(TaskListMsg taskListMsg) {
        Intent intent = new Intent();
        switch (taskListMsg.getRespCode()) {
            case UPDATE_TASK_OK:
                dbManager.updateUserPreference(App.userName, "taskIDs", getTask(), "isTaskIDSynced", 1);//更新数据库数据
                setResult(TASK_INFO, intent);
                finish();
                AppLog.i("update task ids onResponse success!");
                break;
            case UPDATE_TASK_NOK:
                dbManager.updateUserPreference(App.userName, "taskIDs", getTask(), "isTaskIDSynced", 0);//更新数据库数据
                setResult(TASK_INFO, intent);
                finish();
                AppLog.i("update task ids onResponse failed!");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
